////////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2011-2012 www.iflytek.com. All Rights Reserved.
//  This software for customer relationship management system, developed by Noo team.
//  Software code and design for the team, copy rights reserved.
////////////////////////////////////////////////////////////////////////////////

package com.iflytek.ci.common.service.impl;

import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;
import java.util.UUID;

import com.iflytek.ci.common.service.AttachmentService;
import com.iflytek.ci.main.domain.Attachment;
import com.iflytek.ci.main.repository.AttachmentRepository;
import com.mongodb.gridfs.GridFSDBFile;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

/**
 * <p>
 * mongoDB存储数据库逻辑，文件存储服务.
 * </p>
 *
 * @author poplar.yfyang
 * @version 1.0 2012-10-31 12:17 AM
 * @since JDK 1.5
 */
@Service
public class AttachmentServiceImpl implements AttachmentService {
	/** 日志服务 */
	private static Logger logger = LoggerFactory.getLogger(AttachmentServiceImpl.class);
	/** 自动注入 附件服务 */
	@Autowired
	private AttachmentRepository attachmentRepository;

	@Override
	public void add_attachment(Attachment attachment, File file) {
		attachmentRepository.save_file(file.getName(), file);
	}
    @Override
    public void add_attachments(List<Attachment> attachments, File file) {
        attachmentRepository.save_file(file.getName(), file);
    }

	@Override
	public void remove_attachment(String file_name) {
		attachmentRepository.remove_file(file_name);
	}

	@Override
	public void attachment_write_to_output(OutputStream out, String file_name) {
		final GridFSDBFile gridFSDBFile = attachmentRepository.file_form_name(file_name);
		try {
			gridFSDBFile.writeTo(out);
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	@Override
	public String file_attachment_upload(MultipartFile upload_file) {
		File file = null;
		String name = UUID.randomUUID().toString();
		try {
			//文件临时目录存放
			file = new File(System.getProperty("java.io.tmpdir") + File.separator + name);
			FileUtils.writeByteArrayToFile(file, upload_file.getBytes());
			final byte[] fileContext = upload_file.getBytes();
			add_attachment(name, fileContext);
		} catch (IOException e) {
			logger.error("文件读取异常!", e);
			return null;
		} finally {
			FileUtils.deleteQuietly(file);
		}
		return name;
	}

	@Override
	public void add_attachment(String name, byte[] fileContext) {
		attachmentRepository.save_file_byte(name, fileContext);

	}
}
